const { formatTime } = require("../../utils/util");
const wxapi = require("../../utils/wxapi");
const app = getApp();
// pages/login/login.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    menuIndex: 1,
    phoneNum: null,
    timeDown: 60,
    codes: null,
    islogin: false,
    notGetSmsCode: false,
    agreement: false
  },

  /**
   * 选项切换
   * @param {*} e 
   */
  menuChange(e) {
    const menuIndex = e.currentTarget.dataset.menuIndex;
    this.setData({
      menuIndex: Number(menuIndex)
    })
  },

  /**
   * 帐号登录
   */
  ValidateCardByPass(e) {
    const formValue = e.detail.value;
    if (!this.data.agreement) {
      wx.showModal({
        title: '提示信息',
        content: '请先阅读并同意《神通艺术用户协议》、《隐私协议》',
        showCancel: false
      })
      return false;
    }
    if (!formValue.cardNo) {
      wx.showModal({
        title: '提示信息',
        content: '请输入神州通号/手机号/身份证号',
        showCancel: false
      })
      return false;
    }
    if (!formValue.password) {
      wx.showModal({
        title: '提示信息',
        content: '请输入密码',
        showCancel: false
      })
      return false;
    }
    if (!formValue.code) {
      wx.showModal({
        title: '提示信息',
        content: '请输入验证码',
        showCancel: false
      })
      return false;
    } else if (formValue.code !== this.data.codes) {
      wx.showModal({
        title: '提示信息',
        content: '请输入正确验证码',
        showCancel: false
      })
      return false;
    }
    this.setData({
      islogin: true
    })
    const bodyParams = {
      cardNo: formValue.cardNo,
      password: formValue.password
    }
    wxapi.ValidateCardByPass(bodyParams).then(res => {
      this.setData({
        islogin: false
      })
      if (res.code === 20000) {
        wx.setStorageSync('userInfo', JSON.stringify(res.data));
        wx.setStorageSync('token', res.token);
        app.globalData.userInfo = res.data;
        app.globalData.token = res.token;
        this.getSpaceMsg(res.data.cardNo)
      } else {
        wx.showModal({
          title: '提示信息',
          content: res.message,
          showCancel: false
        })
      }
    })
  },

  /**
   * 获取手机号
   */
  getPhoneNum(e) {
    const value = e.detail.value;
    this.data.phoneNum = value;
  },

  /**
   * 获取短信验证码
   */
  getSmsCode() {
    if (this.data.phoneNum) {
      const phoneRxp = /^[1][0-9]{10}$/;
      if (phoneRxp.test(this.data.phoneNum)) {
        this.setData({
          notGetSmsCode: true
        })
        const bodyParams = {
          smsType: 2
        }
        const headers = {
          'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
        }
        wxapi.sendSms(this.data.phoneNum, bodyParams, headers).then(res => {
          if (res.code === 20000) {
            this.countDown();
          } else {
            wx.showModal({
              title: '提示信息',
              content: res.message,
              showCancel: false
            })
          }
        })
      } else {
        wx.showModal({
          title: '提示信息',
          content: '请填写正确手机号',
          showCancel: false
        })
      }
    } else {
      wx.showModal({
        title: '提示信息',
        content: '请填写手机号',
        showCancel: false
      })
    }
  },

  /**
   * 手机号登录
   */
  loginByPhoneAndCode(e) {
    if (!this.data.agreement) {
      wx.showModal({
        title: '提示信息',
        content: '请先阅读并同意《神通艺术用户协议》、《隐私协议》',
        showCancel: false
      })
      return false;
    }
    const formValue = e.detail.value;
    if (!formValue.phoneNum) {
      wx.showModal({
        title: '提示信息',
        content: '请填写正确手机号',
        showCancel: false
      })
      return false;
    }
    if (!formValue.code) {
      wx.showModal({
        title: '提示信息',
        content: '请填写短信验证码',
        showCancel: false
      })
      return false;
    }

    this.setData({
      islogin: true
    })
    wxapi.loginByPhoneAndCode(formValue).then(res => {
      this.setData({
        islogin: false
      })
      if (res.code === 20000) {
        wx.setStorageSync('userInfo', JSON.stringify(res.data));
        wx.setStorageSync('token', res.token);
        app.globalData.userInfo = res.data;
        app.globalData.token = res.token;
        this.getSpaceMsg(res.data.cardNo)

      } else {
        wx.showModal({
          title: '提示信息',
          content: res.message,
          showCancel: false
        })
      }
    })
  },

  /**
   * 获取用户空间信息
   */
  getSpaceMsg(stk) {
    wxapi.selectSpaceMsg({ stk }).then(res => {
      if (res.status === 200) {
        if (res.data.avliableSpace) {
          const curTimestamp = new Date().getTime();
          const expirtDateStr = res.data.expirtDate.replace(/-/g, '/');
          const expirtDate = new Date(expirtDateStr).getTime();
          if ((expirtDate - curTimestamp) < 864000000) {
            wx.showModal({
              title: '提示信息',
              content: `尊敬的神通艺术用户您好！您的艺术品存储空间将于${formatTime(expirtDateStr, 'date')}到期，请您及时关注。若有需要，请致电95130000。`,
              showCancel: false,
              complete: (res) => {
                wx.switchTab({
                  url: '/pages/index/index',
                })
              }
            })
          } else {
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
        } else {
          wx.switchTab({
            url: '/pages/index/index',
          })
        }
      } else {
        wx.switchTab({
          url: '/pages/index/index',
        })
      }
    })
  },

  /**
   * 
   * @param {*} e 
   */
  agreementChange(e) {
    const value = e.detail.value;
    if (value.length > 0) {
      this.setData({
        agreement: true
      })
    } else {
      this.setData({
        agreement: false
      })
    }
  },

  /**
    * 验证码倒计时
    */
  countDown() {
    const timetemp = setInterval(() => {
      this.data.timeDown--;
      if (this.data.timeDown === 0) {
        clearInterval(timetemp);
        this.setData({
          timeDown: 60
        })
      }
      this.setData({
        timeDown: this.data.timeDown
      })
    }, 1000);
  },

  /**
   * 随机验证码
   */
  verification() {
    const vCode = [
      '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
      'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
      'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
      'u', 'v', 'w', 'x', 'y', 'z'
    ];
    let codes = '';
    for (let i = 0; i < 4; i++) {
      const r = Math.floor(Math.random() * vCode.length);
      codes += vCode[r];
    }
    this.setData({
      codes
    })
    // this.codes = codes;
  },

  /**
   * 取消登录
   */
  cancelLogin() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.verification()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})